#include "threadpool.h"

void threadpoolInit(thread_pool_t* pthreadpool,int threadNum){
    pthreadpool->threadNum = threadNum;
    pthreadpool->threads =(pthread_t*)calloc(threadNum,sizeof(pthread_t));
    queueInit(&pthreadpool->queue);    
}

void threadpoolDestroy(thread_pool_t*pthreadpool){
    free(pthreadpool->threads);
    queueDestory(&pthreadpool->queue);
}

void threadpoolStart(thread_pool_t*pthreadpool){
    for(int idx=0;idx<pthreadpool->threadNum;++idx){
        int ret = pthread_create(&pthreadpool->threads[idx],
                                 NULL,
                                 threadFunc,
                                 pthreadpool);
        THREAD_ERROR_CHECK(ret,"pthread_create");

    }
}
void * threadFunc(void * arg){
    printf("sub thread %ld is runing\n", pthread_self());
    thread_pool_t * pthreadpool = (thread_pool_t*)arg;

    while(1) {
        int peerfd = taskDequeue(&pthreadpool->queue);
        if(peerfd > 0) {
           /* char filename[] = "bigfile.avi";
            transferFile(peerfd, filename);*/
            handlEvent(peerfd);
        } else {
            break;
        }
    }
    printf("sub thread %ld is ready to exit\n", pthread_self());
    pthread_exit(0);

}
void handlEvent(int peerfd){
    int epfd = epollCreat();
    struct epoll_event evt[2];
    while(1){
        int nret = epoll_wait(epfd, evt, MAXCONNS, 1000);

        char recvbuff[BUFFSIZE] = {0};
        char order[100]={0};
        char filename[100]={0};
        //接受文件
        int length;
        int ret = recv(peerfd,&length,4,MSG_WAITALL);
        printf(">recvbuff length is %d\n",length);
        ret = recv(peerfd, recvbuff, length, MSG_WAITALL);
        printf(">>1. recvbuff:%s\n",recvbuff);

        if(0 == ret){
            break;
        }

        if(strncmp(recvbuff,"ls",2)==0){
                printf("recvbuff %s aa\n",recvbuff);
                ls(peerfd);
        }else if(strncmp(recvbuff,"pwd",3)==0){
                printf("enter srtncmp :%s \n",recvbuff);
                pwd(peerfd);
        }else if(strncmp(recvbuff,"gets",4)==0){
            printf("--enter train gets\n");
            splitChar(recvbuff,order,filename);
            trainSend(recvbuff,peerfd);
            printf("trainSend recvbuff %s\n",recvbuff);
           do_gets(peerfd,filename);
        }
        else{
                splitChar(recvbuff,order,filename);
                judge(order,filename,peerfd);
        }
        /*if(strcmp(order,"rm") == 0){
            printf(">order have rm\n");
            rm(filename,peerfd);
        }*/
        
        //发送文件给客户端
       // ret = sendn(peerfd,recvbuff,strlen(recvbuff));
        memset(&recvbuff,0,sizeof(recvbuff));
        memset(&order,0,sizeof(order));
        memset(&filename,0,sizeof(filename));
    }



}
